using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace LibraryManagementSystem
{
    public partial class CategoryManagementForm : Form
    {
        private readonly BookService _bookService;
        private List<BookCategory> _categories;

        public CategoryManagementForm()
        {
            InitializeComponent();
            _bookService = new BookService();
        }

        private void CategoryManagementForm_Load(object sender, EventArgs e)
        {
            LoadCategories();
        }

        private void LoadCategories()
        {
            _categories = _bookService.GetAllCategories();
            
            lvCategories.Items.Clear();
            foreach (var category in _categories)
            {
                var item = new ListViewItem(category.CategoryCode);
                item.SubItems.Add(category.CategoryName);
                item.SubItems.Add(GetParentCategoryName(category.ParentId));
                item.SubItems.Add(category.Description);
                item.Tag = category;
                lvCategories.Items.Add(item);
            }
            
            // 设置父分类下拉框
            cmbParentCategory.Items.Clear();
            cmbParentCategory.Items.Add(new ComboBoxItem { Text = "无 (顶级分类)", Value = null });
            foreach (var category in _categories)
            {
                cmbParentCategory.Items.Add(new ComboBoxItem { Text = category.CategoryName, Value = category.Id });
            }
            cmbParentCategory.DisplayMember = "Text";
            cmbParentCategory.ValueMember = "Value";
            cmbParentCategory.SelectedIndex = 0;
        }

        private string GetParentCategoryName(int? parentId)
        {
            if (!parentId.HasValue) return "无";
            
            var parent = _categories.Find(c => c.Id == parentId.Value);
            return parent?.CategoryName ?? "未知";
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            // 验证输入
            if (string.IsNullOrEmpty(txtCategoryCode.Text) || string.IsNullOrEmpty(txtCategoryName.Text))
            {
                MessageBox.Show("请输入分类编码和名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            
            // 准备分类对象
            var category = new BookCategory
            {
                CategoryCode = txtCategoryCode.Text.Trim(),
                CategoryName = txtCategoryName.Text.Trim(),
                Description = txtDescription.Text.Trim()
            };
            
            // 设置父分类
            if (cmbParentCategory.SelectedIndex > 0)
            {
                var selectedParent = cmbParentCategory.SelectedItem as ComboBoxItem;
                category.ParentId = selectedParent?.Value as int?;
            }
            
            // 保存分类
            bool success = _bookService.AddCategory(category);
            
            if (success)
            {
                MessageBox.Show("分类添加成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                ClearForm();
                LoadCategories();
            }
            else
            {
                MessageBox.Show("添加分类失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (lvCategories.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择要更新的分类", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            // 验证输入
            if (string.IsNullOrEmpty(txtCategoryCode.Text) || string.IsNullOrEmpty(txtCategoryName.Text))
            {
                MessageBox.Show("请输入分类编码和名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            
            var selectedCategory = lvCategories.SelectedItems[0].Tag as BookCategory;
            
            // 准备更新对象
            selectedCategory.CategoryCode = txtCategoryCode.Text.Trim();
            selectedCategory.CategoryName = txtCategoryName.Text.Trim();
            selectedCategory.Description = txtDescription.Text.Trim();
            
            // 设置父分类
            if (cmbParentCategory.SelectedIndex > 0)
            {
                var selectedParent = cmbParentCategory.SelectedItem as ComboBoxItem;
                int? newParentId = selectedParent?.Value as int?;
                
                // 防止循环引用
                if (newParentId == selectedCategory.Id)
                {
                    MessageBox.Show("分类不能以自己为父分类", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                
                selectedCategory.ParentId = newParentId;
            }
            else
            {
                selectedCategory.ParentId = null;
            }
            
            // 保存更新
            bool success = _bookService.UpdateCategory(selectedCategory);
            
            if (success)
            {
                MessageBox.Show("分类更新成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                ClearForm();
                LoadCategories();
            }
            else
            {
                MessageBox.Show("更新分类失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (lvCategories.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择要删除的分类", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            var selectedCategory = lvCategories.SelectedItems[0].Tag as BookCategory;
            
            var result = MessageBox.Show($"确定要删除分类 \"{selectedCategory.CategoryName}\" 吗？", "确认删除", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            
            if (result == DialogResult.Yes)
            {
                bool success = _bookService.DeleteCategory(selectedCategory.Id);
                
                if (success)
                {
                    MessageBox.Show("分类删除成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearForm();
                    LoadCategories();
                }
                else
                {
                    MessageBox.Show("无法删除分类，可能存在关联的图书或子分类", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        private void ClearForm()
        {
            txtCategoryCode.Text = string.Empty;
            txtCategoryName.Text = string.Empty;
            txtDescription.Text = string.Empty;
            cmbParentCategory.SelectedIndex = 0;
            lvCategories.SelectedItems.Clear();
        }

        private void lvCategories_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvCategories.SelectedItems.Count > 0)
            {
                var selectedCategory = lvCategories.SelectedItems[0].Tag as BookCategory;
                
                txtCategoryCode.Text = selectedCategory.CategoryCode;
                txtCategoryName.Text = selectedCategory.CategoryName;
                txtDescription.Text = selectedCategory.Description;
                
                // 设置父分类下拉框选择
                if (selectedCategory.ParentId.HasValue)
                {
                    for (int i = 0; i < cmbParentCategory.Items.Count; i++)
                    {
                        var item = cmbParentCategory.Items[i] as ComboBoxItem;
                        if (item.Value is int parentId && parentId == selectedCategory.ParentId.Value)
                        {
                            cmbParentCategory.SelectedIndex = i;
                            break;
                        }
                    }
                }
                else
                {
                    cmbParentCategory.SelectedIndex = 0;
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
    }
} 